// pages/lotteryDetail/complaint/complaint.js
const app = getApp();
const api = require('../../utils/api.js');
const util = require('../../utils/util.js');
const qiniuUploader = require("../../utils/qiniuUploader.js");
let saveImgData = [],
  t, lid;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    compData: [{
      name: '恶意营销',
        type: 0,
        comptype: 1
      },
      {
        name: '侵权',
        type: 0,
        comptype: 2
      },
      {
        name: '不实信息',
        type: 0,
        comptype: 3
      },
      {
        name: '骚扰',
        type: 0,
        comptype: 4
      },
      {
        name: '物流问题',
        type: 0,
        comptype: 5
      },
      {
        name: '退换问题',
        type: 0,
        comptype: 6
      },
      {
        name: '其他违规',
        type: 0,
        comptype: 7
      }
    ],
    comptype: "",
    updataImgData: [],
    compText: "",
    isUploadImg: true,
    phoneName: '',
    repeat: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    t = this;
    saveImgData = [];
    lid = options.lid;
  },
  // 选择投诉内容
  compChoose: function(e) {
    let index = e.currentTarget.dataset.type,
      compData = this.data.compData, comptype = '';
    for (let i in compData) {
      if (i == index){
        compData[i].type=1
        comptype = compData[i].comptype
      }else{
        compData[i].type = 0
      }
    }
    this.setData({
      compData: compData,
      comptype: comptype
    })
  },
  // 上传图片
  upLoadImg: function(e) {
    if (t.data.repeat) {
      t.data.repeat = false;
      var count;
      if (t.data.updataImgData.length) {
        count = 8 - t.data.updataImgData.length;
      } else {
        count = 8;
      }
      wx.chooseImage({
        count: count, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function(imgResult) {
          wx.showLoading({
            title: '图片上传中',
          })
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = [];
          var tempFilePaths = imgResult.tempFilePaths;
          var tempLength = imgResult.tempFilePaths.length;
          var state = 0;
          var imgData = [];
          api.getQnyToken({
            data: {},
            success: res => {
              // 交给七牛上传
              new Promise(function(resolve, reject) {
                for (var i = 0; i < tempFilePaths.length; i++) {
                  qiniuUploader.upload(tempFilePaths[i], (imgResult) => {
                      state++;
                      // '返回需要上传给服务端的图片url', imgResult.imageURL;
                      var image = {};
                      var updataImgData1 = [];
                      image.qnyimg = 'https://' + imgResult.imageURL;
                      image.wximg = tempFilePaths[i];
                      image.order = imgResult.key;
                      updataImgData1.push(image);
                      imgData = imgData.concat(updataImgData1);

                      if (state == tempFilePaths.length) {
                        resolve(imgData);
                      }
                    }, (error) => {
                      reject('error');
                      console.log('error: ' + error);
                    }, {
                      region: 'ECN', // 华东区
                      domain: res.data.result.domain,
                      uptoken: res.data.result.token,
                      key: app.globalData.uid + (new Date().getTime()) + (Math.ceil(Math.random() * 1000)) //生成随机图片名称:用户ID+时间戳+随机数
                    },
                    (progress) => {

                    }, cancelTask => {}
                  );
                }
              }).then(function(imgData) {
                var len = imgData.length;
                // 图片顺序处理
                for (var i = 0; i < len; i++) {
                  for (var j = 0; j < len - 1 - i; j++) {
                    if (imgData[j].order > imgData[j + 1].order) { // 相邻元素两两对比
                      var temp = imgData[j + 1]; // 元素交换
                      imgData[j + 1] = imgData[j];
                      imgData[j] = temp;
                    }
                  }
                }
                // 图片顺序处理 
                saveImgData = saveImgData.concat(imgData)
                t.setData({
                  repeat: true,
                  updataImgData: saveImgData
                })
                if (saveImgData.length > 7) {
                  t.setData({
                    isUploadImg: false
                  })
                }
                wx.hideLoading();
              })
            },
            fail: res => {
              t.data.repeat = true;
            }
          });
        },
        fail: res => {
          t.data.repeat = true;
          util.showToast('上传图片失败', 'none');
        }
      })
    }

  },
  // 删除图片
  delReplyImg: function(e) {
    var t = this;
    var index = e.currentTarget.dataset.index;
    var imgData = t.data.updataImgData;
    imgData.splice(index, 1);
    if (imgData.length == 7) {
      t.setData({
        isUploadImg: true
      })
    }
    saveImgData = imgData;
    t.setData({
      updataImgData: imgData
    })
  },
  // 图片预览
  imgYu: function(e) {
    var src = e.currentTarget.dataset.src;
    var list = e.currentTarget.dataset.list;
    var listData = [];
    listData.push(list);
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: listData // 需要预览的图片http链接列表，需要为数组
    })
  },
  // 投诉文本
  compText: function(e) {
    t.setData({
      compText: e.detail.value
    })
  },
  // 联系方式
  phoneName: function(e) {
    var str = util.subString(e.detail.value, 40, true);
    t.setData({
      phoneName: str
    })
  },
  // 提交
  compSubmit: function(e) {
    if (!t.data.comptype) {
      util.showToast('请选择你要投诉的内容', 'none')
      return;
    }
    if (!t.data.compText) {
      util.showToast('请填写问题描述', 'none')
      return;
    }
    if (!t.data.phoneName) {
      util.showToast('请填写联系方式', 'none')
      return;
    }
    var complian_images = "";
    for (var i = 0; i < t.data.updataImgData.length; i++) {
      complian_images = complian_images + t.data.updataImgData[i].qnyimg + ',';
    }
    api.complain({
      data: {
        lid: lid,
        complain_type: t.data.comptype,
        complain_info: t.data.compText,
        complain_images: complian_images,
        complain_tel: t.data.phoneName,
        formid: e.detail.formId
      },
      success: res => {
        wx.navigateBack({
          delta: 1
        })
        if (res.data.code == 0) {
          setTimeout(function(e) {
            util.showToast('投诉成功', 'none');
          }, 500)
        }
      }
    })
  }
})